<template>
  <div class="app-container">
    <el-row>
      <el-button
        v-hasPermi="['biobank:sample:add']"
        :disabled="ids.length == 0"
        icon="el-icon-plus"
        plain
        size="mini"
        type="primary"
        @click="batchApproval"
      >批量审批
      </el-button>
    </el-row>
    <el-table v-loading="loading" :data="tastList" class="mt10" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="流程名称" prop="instanceName" width="500"/>
      <el-table-column align="center" label="任务节点名称" prop="name"/>
      <el-table-column align="center" label="任务状态" prop="status"/>
      <el-table-column align="center" label="办理人" prop="assignee"/>
      <el-table-column align="center" label="创建时间" prop="createTime"/>

      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['activiti:task:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="examineAndApprove(scope.row)"
          >审批
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 审批对话框 -->
    <el-dialog v-if="open" :title="title" :visible.sync="open" append-to-body width="1680px">
      <!-- 审批详情 -->
      <stock-detail v-if="definitionKey==='stock'" :stock-id="businessKey"></stock-detail>
      <shift-detail v-else-if="definitionKey==='shift'" :shift-id="businessKey"></shift-detail>
      <h2>您的审批：</h2>
      <el-form ref="form" :model="form" class="demo-dynamic" label-width="100px">
        <div v-for="(domain, index) in form.formData" :key="index" :label="domain.controlLable">
          <parser ref="formCustom" :form-conf="domain.json"/>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--批量审批对话框-->
    <el-dialog :visible.sync="batchOpen" append-to-body title="批量审批">
      <el-form ref="forms" :model="forms" class="demo-dynamic" label-width="100px">
        <div v-for="(domain, index) in forms.formData" :key="index" :label="domain.controlLable">
          <parser ref="formCustoms" :form-conf="domain.json"/>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="batchSubmitForm">确 定</el-button>
        <el-button @click="batchCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Parser from 'form-gen-parser'
import StockDetail from '@/views/activiti/stock/StockDetail'
import ShiftDetail from '@/views/activiti/shift/ShiftDetail'
import { formDataSave, formDataSaves, formDataShow, listTask } from '@/api/activiti/task'
import { hideLoading, showLoading } from '@/utils/loading'

export default {
  name: 'Task',
  components: {
    Parser,
    StockDetail,
    ShiftDetail
  },
  data() {
    return {
      id: '',
      definitionKey: '',
      businessKey: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假表格数据
      tastList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        formData: []
      },
      // 表单校验
      rules: {},

      //批量审批
      batchOpen: false,
      forms: {
        formData: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询列表
    getList() {
      this.loading = true
      listTask(this.queryParams).then(response => {
        this.tastList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.definitionKey = '',
        this.businessKey = '',
        this.form = {
          formData: []
        }
      this.resetForm('form')
    },
    // 审批按钮操作
    examineAndApprove(row) {
      this.reset()
      this.definitionKey = row.definitionKey
      this.businessKey = row.businessKey
      this.id = row.id
      formDataShow(row.id).then(response => {
        let formData = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formData.push({
                  type: 'custom',
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.form.formData = formData
        this.open = true
        this.title = '审批'
      })
    },
    /** 提交按钮 */
    submitForm() {
      let custFormRef = this.$refs.formCustom[0]
      let custForm = custFormRef.$refs[custFormRef.formConf.formRef]
      let custData = custFormRef[custFormRef.formConf.formModel]
      let custDesc = {}
      for (let onceForm of this.form.formData) {
        for (let onceField of onceForm.json.fields) {
          if (onceField.__vModel__) {
            custDesc[onceField.__vModel__] = onceField.__config__.label
          } else {
            if (onceField.__config__ && onceField.__config__.children && onceField.__config__.children.length > 0) {
              onceField.__config__.children.forEach(child => {
                custDesc[child.__vModel__] = child.__config__.label
              })
            }
          }
        }
      }
      let params = { data: custData, desc: custDesc }
      // 自定义表单的核验
      custForm.validate()
        .then(e => {
          if (e) {
            showLoading()
            formDataSave(this.id, params).then(response => {
              this.msgSuccess('审批成功')
              hideLoading()
              this.open = false
              this.getList()
            }, error => {
              hideLoading()
            })
          }
        })

    },

    /**
     * @description: 批量审批打开
     * @return {*}
     */
    batchApproval() {
      formDataShow(this.ids[0]).then(response => {
        let formData = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formData.push({
                  type: 'custom',
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.forms.formData = formData
        this.batchOpen = !this.batchOpen
      })
    },

    /**
     * @description: 批量审批提交
     * @return {*}
     */
    batchSubmitForm() {
      let custFormRef = this.$refs.formCustoms[0]
      let custForm = custFormRef.$refs[custFormRef.formConf.formRef]
      let custData = custFormRef[custFormRef.formConf.formModel]
      let custDesc = {}
      for (let onceForm of this.forms.formData) {
        for (let onceField of onceForm.json.fields) {
          if (onceField.__vModel__) {
            custDesc[onceField.__vModel__] = onceField.__config__.label
          } else {
            if (onceField.__config__ && onceField.__config__.children && onceField.__config__.children.length > 0) {
              onceField.__config__.children.forEach(child => {
                custDesc[child.__vModel__] = child.__config__.label
              })
            }
          }
        }
      }
      let params = { data: custData, desc: custDesc }
      // 自定义表单的核验
      custForm.validate()
        .then(e => {
          if (e) {
            showLoading()
            formDataSaves(this.ids, params).then(response => {
              this.msgSuccess('审批成功')
              hideLoading()
              this.batchOpen = !this.batchOpen
              this.getList()
            }, error => {
              hideLoading()
            })
          }
        })
    },

    /**
     * @description: 批量审批取消
     * @return {*}
     */
    batchCancel() {
      this.batchOpen = !this.batchOpen
    },

    /**
     * @description: 多选框选中数据
     * @param selection
     * @return {*}
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    }
  }
}
</script>
